<template>
  <view class="evaluations-container">
    <!-- 下拉刷新 -->
    <scroll-view 
      class="scroll-container"
      scroll-y="true"
      refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
      :lower-threshold="50"
    >
      <!-- 评价统计 -->
      <view class="stats-header">
        <view class="overall-rating">
          <text class="rating-score">{{ overallScore }}</text>
          <view class="stars">
            <text 
              class="star" 
              :class="{ 'filled': index < Math.floor(overallScore) }"
              v-for="(star, index) in 5" 
              :key="index"
            >★</text>
          </view>
          <text class="total-count">共{{ totalCount }}条评价</text>
        </view>
        
        <view class="rating-distribution">
          <view class="rating-item" v-for="item in ratingStats" :key="item.star">
            <text class="star-label">{{ item.star }}星</text>
            <view class="progress-bar">
              <view class="progress" :style="{ width: item.percentage + '%' }"></view>
            </view>
            <text class="count">{{ item.count }}</text>
          </view>
        </view>
      </view>
      
      <!-- 筛选标签 -->
      <view class="filter-tabs">
        <view 
          class="tab-item" 
          :class="{ active: currentFilter === item.key }"
          v-for="item in filterTabs" 
          :key="item.key"
          @click="changeFilter(item.key)"
        >
          {{ item.label }}
          <text class="tab-count" v-if="item.count > 0">({{ item.count }})</text>
        </view>
      </view>
      
      <!-- 评价列表 -->
      <view class="evaluation-list">
        <view 
          class="evaluation-item" 
          v-for="item in filteredEvaluations" 
          :key="item.id"
        >
          <view class="user-info">
            <image 
              class="avatar" 
              :src="item.avatar || '/static/images/default-avatar.png'" 
              @error="handleAvatarError"
            />
            <view class="user-details">
              <text class="nickname">{{ item.nickname }}</text>
              <view class="rating-info">
                <view class="stars">
                  <text 
                    class="star" 
                    :class="{ filled: index < item.rating }"
                    v-for="(star, index) in 5" 
                    :key="index"
                  >★</text>
                </view>
                <text class="date">{{ formatDate(item.createTime) }}</text>
              </view>
            </view>
          </view>
          
          <view class="content">
            <text class="comment">{{ item.content }}</text>
            
            <!-- 评价图片 -->
            <view class="images" v-if="item.images && item.images.length">
              <image 
                class="comment-image"
                v-for="(img, index) in item.images" 
                :key="index"
                :src="img"
                mode="aspectFill"
                @click="previewImage(img, item.images)"
                @error="handleImageError"
              />
            </view>
            
            <!-- 规格信息 -->
            <view class="spec-info" v-if="item.spec">
              <text class="spec">规格：{{ item.spec }}</text>
            </view>
          </view>
          
          <!-- 商家回复 -->
          <view class="merchant-reply" v-if="item.reply">
            <view class="reply-header">
              <uni-icons type="shop" size="16" color="#ff6b6b"></uni-icons>
              <text class="merchant-label">商家回复</text>
            </view>
            <text class="reply-content">{{ item.reply }}</text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多状态 -->
      <view class="load-more" v-if="hasMore || loading">
        <view class="load-more-content" v-if="loading">
          <view class="loading-spinner"></view>
          <text class="load-text">加载中...</text>
        </view>
        <view class="load-more-content" v-else-if="hasMore">
          <text class="load-text">上拉加载更多</text>
        </view>
        <view class="load-more-content" v-else>
          <text class="load-text">没有更多评价了</text>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && filteredEvaluations.length === 0">
        <image 
          class="empty-image"
          src="https://img.icons8.com/clouds/200/000000/no-data.png" 
          mode="aspectFit"
        />
        <text class="empty-text">暂无相关评价</text>
        <view class="empty-tip">
          <text>{{ getEmptyTip() }}</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getGoodsComments } from '@/api/goods'

export default {
  data() {
    return {
      goodsId: '',
      currentFilter: 'all',
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      hasMore: true,
      loading: false,
      refreshing: false,
      overallScore: 4.8,
      
      filterTabs: [
        { key: 'all', label: '全部', count: 0 },
        { key: 'good', label: '好评', count: 0 },
        { key: 'medium', label: '中评', count: 0 },
        { key: 'bad', label: '差评', count: 0 },
        { key: 'image', label: '有图', count: 0 }
      ],
      
      evaluations: []
    }
  },
  
  computed: {
    ratingStats() {
      const stats = [5, 4, 3, 2, 1].map(star => {
        const count = this.evaluations.filter(item => item.rating === star).length
        const percentage = this.evaluations.length > 0 ? (count / this.evaluations.length) * 100 : 0
        return { star, count, percentage: Math.round(percentage) }
      })
      return stats
    },
    
    filteredEvaluations() {
      let filtered = this.evaluations
      
      switch (this.currentFilter) {
        case 'good':
          filtered = this.evaluations.filter(item => item.rating >= 4)
          break
        case 'medium':
          filtered = this.evaluations.filter(item => item.rating === 3)
          break
        case 'bad':
          filtered = this.evaluations.filter(item => item.rating <= 2)
          break
        case 'image':
          filtered = this.evaluations.filter(item => item.images && item.images.length > 0)
          break
        default:
          filtered = this.evaluations
      }
      
      return filtered
    }
  },
  
  methods: {
    // 切换筛选条件
    changeFilter(key) {
      this.currentFilter = key
      this.updateFilterCounts()
    },
    
    // 更新筛选标签数量
    updateFilterCounts() {
      this.filterTabs.forEach(tab => {
        switch (tab.key) {
          case 'all':
            tab.count = this.evaluations.length
            break
          case 'good':
            tab.count = this.evaluations.filter(item => item.rating >= 4).length
            break
          case 'medium':
            tab.count = this.evaluations.filter(item => item.rating === 3).length
            break
          case 'bad':
            tab.count = this.evaluations.filter(item => item.rating <= 2).length
            break
          case 'image':
            tab.count = this.evaluations.filter(item => item.images && item.images.length > 0).length
            break
        }
      })
    },
    
    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      this.currentPage = 1
      this.hasMore = true
      this.evaluations = []
      
      try {
        await this.loadEvaluations(true)
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        })
      } catch (error) {
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        })
      } finally {
        this.refreshing = false
      }
    },
    
    // 上拉加载更多
    async onLoadMore() {
      if (!this.hasMore || this.loading) return
      
      this.currentPage++
      await this.loadEvaluations(false)
    },
    
    // 加载评价数据
    async loadEvaluations(isRefresh = false) {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const result = await getGoodsComments({
          goodsId: this.goodsId,
          page: this.currentPage,
          pageSize: this.pageSize,
          rating: this.currentFilter === 'all' ? null : this.currentFilter
        })
        
        if (result && result.items) {
          const newEvaluations = result.items.map(item => ({
            id: item.comment_id,
            nickname: item.customer_name || '匿名用户',
            avatar: item.customer_avatar || '',
            content: item.reply_content || '用户没有留下评价',
            createTime: item.create_time || item.createTime || '',
            images: item.images || [],
            spec: item.spec_name || '',
            score: item.rating || 5
          }))
          
          if (this.currentPage === 1) {
            this.evaluations = newEvaluations
          } else {
            this.evaluations.push(...newEvaluations)
          }
          
          this.hasMore = newEvaluations.length >= this.pageSize
          this.totalCount = result.total || 0
          
          // 计算总体评分
          if (this.evaluations.length > 0) {
            const totalRating = this.evaluations.reduce((sum, item) => sum + item.score, 0)
            this.overallScore = Number((totalRating / this.evaluations.length).toFixed(1))
          }
          
          // 更新筛选标签数量
          this.updateFilterCounts()
          
        } else {
          this.hasMore = false
          if (isRefresh) {
            this.loadMockData()
          }
        }
        
      } catch (error) {
        uni.showToast({
          title: '获取评价失败',
          icon: 'none'
        })
        if (this.currentPage === 1) {
          this.evaluations = []
        }
        this.hasMore = false
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 加载模拟数据
    loadMockData() {
      const mockData = [
        {
          id: 1,
          nickname: '用户***1',
          avatar: 'https://img.icons8.com/clouds/100/000000/user.png',
          rating: 5,
          content: '商品质量很好，物流也很快，包装精美，非常满意！服务态度也很好，下次还会继续购买。',
          images: [
            'https://img.icons8.com/clouds/200/000000/product.png',
            'https://img.icons8.com/clouds/200/000000/box.png'
          ],
          spec: '经典款/白色/M',
          createTime: '2024-01-15',
          reply: '谢谢您的好评，我们会继续努力为您提供优质的商品和服务！'
        },
        {
          id: 2,
          nickname: '用户***2',
          avatar: 'https://img.icons8.com/clouds/100/000000/user.png',
          rating: 4,
          content: '总体还不错，就是颜色和图片有一点点差别，不过质量挺好的，物流很快。',
          images: [],
          spec: '时尚款/黑色/L',
          createTime: '2024-01-14',
          reply: null
        },
        {
          id: 3,
          nickname: '用户***3',
          avatar: 'https://img.icons8.com/clouds/100/000000/user.png',
          rating: 5,
          content: '非常喜欢，质量超出预期，已经推荐给朋友了！包装很精美，是正品。',
          images: [
            'https://img.icons8.com/clouds/200/000000/shopping-bag.png'
          ],
          spec: '潮流款/红色/S',
          createTime: '2024-01-13',
          reply: null
        },
        {
          id: 4,
          nickname: '用户***4',
          avatar: 'https://img.icons8.com/clouds/100/000000/user.png',
          rating: 3,
          content: '商品一般般，价格稍微有点贵，不过服务还可以。',
          images: [],
          spec: '基础款/蓝色/XL',
          createTime: '2024-01-12',
          reply: '感谢您的评价，我们会努力改进商品质量，给您更好的购物体验。'
        }
      ]
      
      this.evaluations = mockData
      this.totalCount = mockData.length
      this.updateFilterCounts()
      
      // 计算评分
      const totalRating = mockData.reduce((sum, item) => sum + item.rating, 0)
      this.overallScore = Number((totalRating / mockData.length).toFixed(1))
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) return '今天'
      if (days === 1) return '昨天'
      if (days < 7) return `${days}天前`
      if (days < 30) return `${Math.floor(days / 7)}周前`
      if (days < 365) return `${Math.floor(days / 30)}个月前`
      return `${Math.floor(days / 365)}年前`
    },
    
    // 获取空状态提示
    getEmptyTip() {
      switch (this.currentFilter) {
        case 'good':
          return '还没有好评，快来留下第一个好评吧！'
        case 'medium':
          return '暂无中评'
        case 'bad':
          return '暂无差评，说明商品质量不错哦！'
        case 'image':
          return '暂无图片评价'
        default:
          return '暂无评价，快来留下第一个评价吧！'
      }
    },
    
    // 预览图片
    previewImage(current, urls) {
      uni.previewImage({
        current,
        urls
      })
    },
    
    // 头像加载失败处理
    handleAvatarError(e) {
      e.target.src = 'https://img.icons8.com/clouds/100/000000/user.png'
    },
    
    // 图片加载失败处理
    handleImageError(e) {
      e.target.src = 'https://img.icons8.com/clouds/200/000000/no-image.png'
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.goodsId = options.id
      this.loadEvaluations()
    }
  },
  
  onShow() {
    // 页面显示时刷新数据
    if (this.evaluations.length === 0) {
      this.loadEvaluations(true)
    }
  }
}
</script>

<style lang="scss" scoped>
.evaluations-container {
  background: linear-gradient(180deg, #f8f9ff 0%, #f5f6fa 100%);
  min-height: 100vh;
}

.scroll-container {
  height: 100vh;
}

// 统计头部优化
.stats-header {
  background: linear-gradient(135deg, #fff 0%, #f8f9ff 100%);
  padding: 40rpx;
  margin-bottom: 20rpx;
  border-radius: 0 0 24rpx 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
  
  .overall-rating {
    text-align: center;
    padding-bottom: 40rpx;
    border-bottom: 2rpx solid #f0f4f8;
    margin-bottom: 40rpx;
    
    .rating-score {
      font-size: 80rpx;
      font-weight: 700;
      color: #ff6b6b; /* fallback for browsers that don't support background-clip: text */
      display: block;
      margin-bottom: 16rpx;
      background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
      -webkit-background-clip: text;
      background-clip: text;
      -webkit-text-fill-color: transparent;
      color: transparent; /* standard fallback */
    }
    
    .stars {
      margin-bottom: 16rpx;
      
      .star {
        font-size: 36rpx;
        margin: 0 4rpx;
        transition: color 0.3s ease;
        
        &.filled {
          color: #ffd700;
        }
        
        &:not(.filled) {
          color: #e2e8f0;
        }
      }
    }
    
    .total-count {
      font-size: 28rpx;
      color: #718096;
    }
  }
  
  .rating-distribution {
    .rating-item {
      display: flex;
      align-items: center;
      margin-bottom: 24rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .star-label {
        width: 80rpx;
        font-size: 28rpx;
        color: #4a5568;
        font-weight: 500;
      }
      
      .progress-bar {
        flex: 1;
        height: 16rpx;
        background: #f0f4f8;
        border-radius: 8rpx;
        margin: 0 20rpx;
        overflow: hidden;
        
        .progress {
          height: 100%;
          background: linear-gradient(90deg, #ff6b6b, #ff8e8e);
          border-radius: 8rpx;
          transition: width 0.8s ease;
        }
      }
      
      .count {
        width: 60rpx;
        text-align: right;
        font-size: 26rpx;
        color: #718096;
        font-weight: 500;
      }
    }
  }
}

// 筛选标签优化
.filter-tabs {
  display: flex;
  background: #fff;
  padding: 0 16rpx;
  margin-bottom: 20rpx;
  border-radius: 20rpx;
  margin: 0 16rpx 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 32rpx 16rpx;
    font-size: 28rpx;
    color: #718096;
    border-bottom: 4rpx solid transparent;
    transition: all 0.3s ease;
    position: relative;
    
    .tab-count {
      font-size: 22rpx;
      color: #a0aec0;
      margin-left: 4rpx;
    }
    
    &.active {
      color: #ff6b6b;
      border-bottom-color: #ff6b6b;
      font-weight: 600;
      
      .tab-count {
        color: #ff6b6b;
      }
    }
  }
}

// 评价列表优化
.evaluation-list {
  .evaluation-item {
    background: #fff;
    margin: 0 16rpx 20rpx;
    padding: 32rpx;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
    transition: transform 0.3s ease;
    
    &:active {
      transform: translateY(2rpx);
    }
    
    .user-info {
      display: flex;
      margin-bottom: 24rpx;
      
      .avatar {
        width: 88rpx;
        height: 88rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        border: 3rpx solid #f0f4f8;
      }
      
      .user-details {
        flex: 1;
        
        .nickname {
          font-size: 32rpx;
          color: #2d3748;
          font-weight: 600;
          display: block;
          margin-bottom: 12rpx;
        }
        
        .rating-info {
          display: flex;
          align-items: center;
          
          .stars {
            margin-right: 20rpx;
            
            .star {
              font-size: 24rpx;
              margin-right: 4rpx;
              
              &.filled {
                color: #ffd700;
              }
              
              &:not(.filled) {
                color: #e2e8f0;
              }
            }
          }
          
          .date {
            font-size: 24rpx;
            color: #a0aec0;
          }
        }
      }
    }
    
    .content {
      .comment {
        font-size: 30rpx;
        line-height: 1.6;
        color: #4a5568;
        display: block;
        margin-bottom: 20rpx;
      }
      
      .images {
        display: flex;
        flex-wrap: wrap;
        gap: 12rpx;
        margin-bottom: 20rpx;
        
        .comment-image {
          width: 160rpx;
          height: 160rpx;
          border-radius: 16rpx;
          object-fit: cover;
          border: 2rpx solid #f0f4f8;
          transition: transform 0.3s ease;
          
          &:active {
            transform: scale(0.95);
          }
        }
      }
      
      .spec-info {
        .spec {
          font-size: 26rpx;
          color: #718096;
          background: #f7fafc;
          padding: 12rpx 16rpx;
          border-radius: 12rpx;
          border: 1rpx solid #e2e8f0;
          display: inline-block;
        }
      }
    }
    
    .merchant-reply {
      margin-top: 24rpx;
      background: linear-gradient(135deg, #f8f9ff 0%, #f0f4f8 100%);
      padding: 24rpx;
      border-radius: 16rpx;
      border-left: 4rpx solid #ff6b6b;
      
      .reply-header {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;
        
        .merchant-label {
          font-size: 26rpx;
          color: #ff6b6b;
          font-weight: 600;
          margin-left: 8rpx;
        }
      }
      
      .reply-content {
        font-size: 28rpx;
        line-height: 1.5;
        color: #4a5568;
      }
    }
  }
}

// 加载状态
.load-more {
  padding: 40rpx;
  
  .load-more-content {
    display: flex;
    align-items: center;
    justify-content: center;
    
    .loading-spinner {
      width: 32rpx;
      height: 32rpx;
      border: 3rpx solid #f0f4f8;
      border-top: 3rpx solid #ff6b6b;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-right: 12rpx;
    }
    
    .load-text {
      font-size: 28rpx;
      color: #a0aec0;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 空状态优化
.empty-state {
  text-align: center;
  padding: 120rpx 40rpx;
  
  .empty-image {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 32rpx;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: 32rpx;
    color: #4a5568;
    font-weight: 500;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .empty-tip {
    font-size: 26rpx;
    color: #a0aec0;
    line-height: 1.4;
  }
}

// 响应式优化
@media (max-width: 750rpx) {
  .filter-tabs {
    .tab-item {
      font-size: 26rpx;
      padding: 28rpx 12rpx;
    }
  }
  
  .evaluation-list {
    .evaluation-item {
      .content {
        .images {
          .comment-image {
            width: 140rpx;
            height: 140rpx;
          }
        }
      }
    }
  }
}
</style> 